import { randomRoomID }  from '../../utils/common'
import imClient from '../../utils/im-client'
import TRTC from 'trtc-wx-sdk'
let that = null
const app = getApp()
Page({
  data: {
    _rtcConfig: {
      sdkAppID: '', // 必要参数 开通实时音视频服务创建应用后分配的 sdkAppID
      userID: '', // 必要参数 用户 ID 可以由您的帐号系统指定
      userSig: '', // 必要参数 身份签名，相当于登录密码的作用
    },
    pusher: null,
    playerList: [],
    seatId: null,
    currentVideo: -1,
    msgWindow: false,
    signWindow: false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    console.log('room onload', options)
    wx.setKeepScreenOn({
      keepScreenOn: true,
    })
    this.TRTC = new TRTC(this)
    await imClient.init(options.sdkAppID)
    await imClient.login({ userID:options.userID, userSig: options.userSig })
    await imClient.joinGroup(options.roomID)
    await imClient.updateMyProfile({
      nick: app.globalData.userInfo.nickName,
      avatar: app.globalData.userInfo.avatarUrl
    })
    this.init(options)
    this.bindTRTCRoomEvent()
    this.enterRoom({ roomID: options.roomID })
  },

  onReady() {
    console.log('room ready')
    that = this
    imClient.$on('CUSTOM_MESSAGE_C2C',this.messageEvent)
    imClient.$on('CUSTOM_MESSAGE_GROUP',this.messageGroupEvent)
  },
  async onUnload() {
    console.log('room unload')
    imClient.$off('CUSTOM_MESSAGE_C2C',this.messageEvent)
    imClient.$off('CUSTOM_MESSAGE_GROUP',this.messageGroupEvent)
    await imClient.quitGroup()
    imClient.messageEventClose()
    imClient.logout()
  },
  init(options) {
    // pusher 初始化参数
    const pusherConfig = {
      beautyLevel: 9
    }
    const pusher = this.TRTC.createPusher(pusherConfig)
    console.log(pusher.pusherAttributes, '000')
    this.setData({
      _rtcConfig: {
        userID: options.userID,
        sdkAppID: options.sdkAppID,
        userSig: options.userSig,
      },
      pusher: pusher.pusherAttributes
    })
  },

  enterRoom(options) {
    const roomID = options.roomID || randomRoomID()
    const config =  Object.assign(this.data._rtcConfig, { roomID })
    this.setData({
      pusher: this.TRTC.enterRoom(config),
    }, () => {
      this.TRTC.getPusherInstance().start() // 开始推流（autoPush的模式下不需要）
    })
  },

  exitRoom() {
    const result = this.TRTC.exitRoom()
    this.setData({
      pusher: result.pusher,
      playerList: result.playerList,
    })
  },

  // 设置 pusher 属性
  setPusherAttributesHandler(options) {
    this.setData({
      pusher: this.TRTC.setPusherAttributes(options),
    })
  },

  // 设置某个 player 属性
  setPlayerAttributesHandler(player, options) {
    this.setData({
      playerList: this.TRTC.setPlayerAttributes(player.streamID, options),
    })
  },

  // 事件监听
  bindTRTCRoomEvent() {
    const TRTC_EVENT = this.TRTC.EVENT
    // 初始化事件订阅
    this.TRTC.on(TRTC_EVENT.LOCAL_JOIN, (event) => {
      console.log('* room LOCAL_JOIN', event)
      // // 进房成功，触发该事件后可以对本地视频和音频进行设置
      this.setPusherAttributesHandler({ enableCamera: true })
      this.setPusherAttributesHandler({ enableMic: true })
    })
    this.TRTC.on(TRTC_EVENT.LOCAL_LEAVE, (event) => {
      console.log('* room LOCAL_LEAVE', event)
    })
    this.TRTC.on(TRTC_EVENT.ERROR, (event) => {
      console.log('* room ERROR', event)
    })
    // 远端用户退出
    this.TRTC.on(TRTC_EVENT.REMOTE_USER_LEAVE, (event) => {
      const { playerList } = event.data
      this.setData({
        playerList: playerList
      })
      console.log('* room REMOTE_USER_LEAVE', event)
    })
    // 远端用户推送视频
    this.TRTC.on(TRTC_EVENT.REMOTE_VIDEO_ADD, (event) => {
      console.log('* room REMOTE_VIDEO_ADD',  event)
      const { player } = event.data
      // 开始播放远端的视频流，默认是不播放的
      this.setPlayerAttributesHandler(player, { muteVideo: false })
    })
    // 远端用户取消推送视频
    this.TRTC.on(TRTC_EVENT.REMOTE_VIDEO_REMOVE, (event) => {
      console.log('* room REMOTE_VIDEO_REMOVE', event)
      const { player } = event.data
      this.setPlayerAttributesHandler(player, { muteVideo: true })
    })
    // 远端用户推送音频
    this.TRTC.on(TRTC_EVENT.REMOTE_AUDIO_ADD, (event) => {
      console.log('* room REMOTE_AUDIO_ADD', event)
      const { player } = event.data
      this.setPlayerAttributesHandler(player, { muteAudio: false })
    })
    // 远端用户取消推送音频
    this.TRTC.on(TRTC_EVENT.REMOTE_AUDIO_REMOVE, (event) => {
      console.log('* room REMOTE_AUDIO_REMOVE', event)
      const { player } = event.data
      this.setPlayerAttributesHandler(player, { muteAudio: true })
    })
  },

  // 是否订阅某一个player Audio
  _mutePlayerAudio(event) {
    const player = event.currentTarget.dataset.value
    if (player.hasAudio && player.muteAudio) {
      this.setPlayerAttributesHandler(player, { muteAudio: false })
      return
    }
    if (player.hasAudio && !player.muteAudio) {
      this.setPlayerAttributesHandler(player, { muteAudio: true })
      return
    }
  },

  // 订阅 / 取消订阅某一个player Video
  _mutePlayerVideo(event) {
    const player = event.currentTarget.dataset.value
    if (player.hasVideo && player.muteVideo) {
      this.setPlayerAttributesHandler(player, { muteVideo: false })
      return
    }
    if (player.hasVideo && !player.muteVideo) {
      this.setPlayerAttributesHandler(player, { muteVideo: true })
      return
    }
  },

  // 挂断退出房间
  _hangUp() {
    this.exitRoom()
    wx.navigateBack({
      delta: 1,
    })
  },

  // 设置美颜
  _setPusherBeautyHandle() {
    const  beautyLevel = this.data.pusher.beautyLevel === 0 ? 9 : 0
    this.setPusherAttributesHandler({ beautyLevel })
  },

  // 发布 / 取消发布 Audio
  _pusherAudioHandler() {
    if (this.data.pusher.enableMic) {
      this.setPusherAttributesHandler({ enableMic: false })
    } else {
      this.setPusherAttributesHandler({ enableMic: true })
    }
  },

  _pusherSwitchCamera() {
    const  frontCamera = this.data.pusher.frontCamera === 'front' ? 'back' : 'front'
    this.TRTC.getPusherInstance().switchCamera(frontCamera)
  },

  _setPlayerSoundMode() {
    if (this.data.playerList.length === 0) {
      return
    }
    const player = this.TRTC.getPlayerList()
    const soundMode = player[0].soundMode === 'speaker' ? 'ear' : 'speaker'
    this.setPlayerAttributesHandler(player[0], { soundMode })
  },
  // 请保持跟 wxml 中绑定的事件名称一致
  _pusherStateChangeHandler(event) {
    this.TRTC.pusherEventHandler(event)
  },
  _pusherNetStatusHandler(event) {
    this.TRTC.pusherNetStatusHandler(event)
  },
  _pusherErrorHandler(event) {
    this.TRTC.pusherErrorHandler(event)
  },
  _pusherBGMStartHandler(event) {
    this.TRTC.pusherBGMStartHandler(event)
  },
  _pusherBGMProgressHandler(event) {
    this.TRTC.pusherBGMProgressHandler(event)
  },
  _pusherBGMCompleteHandler(event) {
    this.TRTC.pusherBGMCompleteHandler(event)
  },
  _pusherAudioVolumeNotify(event) {
    this.TRTC.pusherAudioVolumeNotify(event)
  },
  _playerStateChange(event) {
    this.TRTC.playerEventHandler(event)
  },
  _playerFullscreenChange(event) {
    this.TRTC.playerFullscreenChange(event)
  },
  _playerNetStatus(event) {
    this.TRTC.playerNetStatus(event)
  },
  _playerAudioVolumeNotify(event) {
    this.TRTC.playerAudioVolumeNotify(event)
  },
  // 切换视频画面
  changeCurrentVideo(e){
    if(this.data.playerList===0||this.data.playerList>2) return
    this.setData({
      currentVideo:e.currentTarget.dataset.index
    })
  },
  // 子组件修改父组件方法
  updateData(options){
    console.log('options',options)
    this.setData(options.detail)
  },
  // 切换聊天框
  changeImgWindow(){
    this.setData({
      msgWindow:!this.data.msgWindow
    })
  },
  // C2C指令消息回调
  messageEvent (res) {
    console.log('res')
    if (res.length > 0) {
      that.setData({
        seatId: res[0].from
      })
      const {description,data} = res[0].payload
      if(description==='DataUpload'){
        console.log('资料补传',data)
        that.dataUploadEvent(res[0].from)
      } else if (description==='ViewInformation'){
        console.log('查看文档',data)
        that.viewInformationEvent(res[0].from)
      } else if (description==='ElectronicSignature'){
        console.log('电子签名',data)
        that.electronicSignature(res[0].from)
      }
    }
  },
  // 全家指令消息回调
  messageGroupEvent(res){
    if(res.length>0){
      const {description,data} = res[0].payload
      if (description==='CloseVideo'){
        console.log('关闭视频',data)
        that.closeVideo(res[0].from)
      }
    }
  },
  // 资料补传
  dataUploadEvent(id){
    wx.showModal({
      title: '提示',
      content: '请进行资料补传',
      success (res) {
        if (res.confirm) {
          imClient.sendCustomMessage({
            id,
            description: 'DataUpload',
            data:JSON.stringify({status:'padding'})
          },'C2C')
          wx.chooseImage({
            sizeType: ['compressed'],
            sourceType: ['album','camera'],
            success (res) {
              // tempFilePath可以作为img标签的src属性显示图片
              const tempFilePaths = res.tempFilePaths
              console.log('tempFilePaths',tempFilePaths)
              imClient.sendCustomMessage({
                id,
                description: 'DataUpload',
                data:JSON.stringify({status:'success'})
              },'C2C')
            }
          })
        } else if (res.cancel) {
          imClient.sendCustomMessage({
            id,
            description: 'DataUpload',
            data:JSON.stringify({status:'cancel'})
          },'C2C')
        }
      }
    })
  },
  // 查看文档
  viewInformationEvent(id) {
    wx.showModal({
      title: '提示',
      content: '请进行资料查看',
      success (res) {
        if (res.confirm) {
          imClient.sendCustomMessage({
            id,
            description: 'ViewInformation',
            data:JSON.stringify({status:'padding'})
          },'C2C')
          wx.previewImage({
            urls: [
              'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
              'https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg',
              'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg',
              'https://fuss10.elemecdn.com/d/e6/c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg',
              'https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg',
              'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg'
            ], // 需要预览的图片http链接列表
            success: () => {
              imClient.sendCustomMessage({
                id,
                description: 'ViewInformation',
                data:JSON.stringify({status:'success'})
              },'C2C')
            },
            fail: (err) => {
              console.log('err',err)
            }
          })
        } else if (res.cancel) {
          imClient.sendCustomMessage({
            id,
            description: 'ViewInformation',
            data:JSON.stringify({status:'cancel'})
          },'C2C')
        }
      }
    })
  },
  //  电子签名
  electronicSignature(id) {
    const that = this
    wx.showModal({
      title: '提示',
      content: '请进行电子签名',
      success (res) {
        if (res.confirm) {
          imClient.sendCustomMessage({
            id,
            description: 'ElectronicSignature',
            data:JSON.stringify({status:'padding'})
          },'C2C')
          that.setData({
            signWindow: true
          })
        } else if (res.cancel) {
          imClient.sendCustomMessage({
            id,
            description: 'ElectronicSignature',
            data:JSON.stringify({status:'cancel'})
          },'C2C')
        }
      }
    })
  },
  // 结束视频
  closeVideo(id){
    wx.showModal({
      title: '提示',
      content: '视频服务已经结束',
      showCancel: false,
      success (res) {
        if (res.confirm) {
          wx.exitMiniProgram({
            success: () => {
              imClient.sendCustomMessage({
                id,
                description: 'CloseVideo',
                data:JSON.stringify({status:'success'})
              },'C2C')
            }
          })
        }
      },
      fail:(err)=>{
        console.log('err',err)
      }
    })
  }
})

